#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->expand_btn->setEnabled(false);
    ui->close_btn->setEnabled(false);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_open_file_btn_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this, "选择一个文件", QDir::currentPath(), "*.txt");
    QFile file(filePath);
    if(!file.open(QIODevice::ReadOnly)){
        QMessageBox::warning(this, "警告", "请选择一个正确的文件");
    }
    else{
        this->ui->plainTextEdit->setPlainText(QString(file.readAll()));
    }
}

void Widget::on_start_btn_clicked()
{
    auto model = new QStandardItemModel(this);
    QString buffer = ui->plainTextEdit->toPlainText();
    buffer += "\n";
    // qDebug() << buffer;
    Scanner scanner(buffer.toStdString());
    auto tokens = scanner.getTokens();
    Parser parser(tokens);
    TreeNode* root = nullptr;
    try {
        root = parser.getSyntaxTree();
    } catch (const QException &e) {
        QMessageBox::warning(this, "警告", "请在确认语法无误后重试");
        return;
    }
    std::queue<TreeNode*> node_qu;
    std::queue<QStandardItem*>item_qu;
    node_qu.push(root);
    auto rootItem = new QStandardItem;
    item_qu.push(rootItem);
    model->appendRow(rootItem);
    int lastCount = 1;
    int thisCount = 0;
    int lineCount = 0;
    while (!node_qu.empty()) {
        while (lastCount--) {
            auto front = node_qu.front();
            node_qu.pop();
            auto item = item_qu.front();
            item_qu.pop();
            if (front->leaf_str.empty()) {
                item->setText(QString::fromStdString(branchType2str[front->branch_type]));
            }
            else {
                item->setText(QString::fromStdString(front->leaf_str));
            }
            for (auto child : front->children) {
                node_qu.push(child);
                auto childItem = new QStandardItem;
                item->appendRow(childItem);
                item_qu.push(childItem);
                thisCount++;
            }
        }
        lastCount = thisCount;
        thisCount = 0;
        lineCount++;
    }
    ui->treeView->setModel(model);
    ui->treeView->setHeaderHidden(true);
    ui->expand_btn->setEnabled(true);
    ui->close_btn->setEnabled(true);
    // 词法分析
    std::string cf = "";
    for (auto token: tokens){
        cf += token.str;
        cf += "\t";
        cf += tokenType2str[token.type];
        cf += "\n";
    }
    ui->textBrowser->setText(QString::fromStdString(cf));
}

void Widget::on_plainTextEdit_textChanged()
{
    ui->expand_btn->setEnabled(false);
    ui->close_btn->setEnabled(false);
}

void Widget::on_expand_btn_clicked()
{
    int depth = ui->spinBox->value();
    ui->spinBox->setValue(depth+1);
    ui->treeView->expandToDepth(depth);
}

void Widget::on_close_btn_clicked()
{
    ui->treeView->collapseAll();
    ui->spinBox->setValue(1);
}
